﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using Caliburn.Micro;
using YiJing.Model;
using YiJing.Properties;
using YiJing.Tasks;

namespace YiJing.ViewModels
{
    [Export(typeof(IShell))]
    public sealed class ShellViewModel : Screen, IShell
    {
        private readonly HexagramFigure[] _hexagramList = HexagramFigure.AllFigures.ToArray();
        private HexagramViewModel _hexagram;

        public ShellViewModel()
        {
            DisplayName = Resources.Caption_HexagramGadget;
            Hexagram = new HexagramViewModel();

            Generate();
        }

        public int SelectedValue
        {
            get { return Hexagram.Figure.Value - 1; }
            set { _hexagram.Figure = _hexagramList[value]; }
        }

        public object List
        {
            get { return _hexagramList; }
        }

        public HexagramViewModel Hexagram
        {
            get { return _hexagram; }
            set
            {
                if (_hexagram != null) _hexagram.OnFigureChanged -= OnFigureChanged;

                _hexagram = value;
                _hexagram.PropertyChanged += OnFigureChanged;
            }
        }

        public bool CanMove
        {
            get { return Hexagram.Figure.IsMoving; }
        }

        public void Move()
        {
            Hexagram.Figure = new HexagramFigure(Hexagram.Figure.MovedLines);
        }

        public void Flip()
        {
            Hexagram.Figure = Hexagram.Figure.Reversed();
        }

        public void Generate()
        {
            var series = new Random();
            var result = HexagramFigure.FromValue(series.Next(1, HexagramFigure.MaxValue + 1));

            foreach (var line in result.Lines)
                line.IsMoving = series.Next(0, 2) == 1;

            Hexagram.Figure = result;
        }

        public IEnumerable<IResult> GenerateFromToss()
        {
            var task = Show.Dialog<CoinTossViewModel>();
            yield return task;

            Hexagram.Figure = task.Dialog.Result;
        }

        private void OnFigureChanged(object sender, EventArgs e)
        {
            NotifyOfPropertyChange(() => SelectedValue);
            NotifyOfPropertyChange(() => CanMove);
        }
    }
}
